package com.liqing.movecomment.controller;

import com.github.pagehelper.PageInfo;
import com.liqing.movecomment.entity.User;
import com.liqing.movecomment.entity.UserChangeDto;
import com.liqing.movecomment.entity.UserDTO;
import com.liqing.movecomment.enums.Constent;
import com.liqing.movecomment.enums.RedisConstant;
import com.liqing.movecomment.exception.CustomException;
import com.liqing.movecomment.service.UserService;
import com.liqing.movecomment.util.JwtUtils;
import com.liqing.movecomment.util.RedisUtils;
import com.liqing.movecomment.util.ThreadLocalUtils;
import com.liqing.movecomment.vo.UserRegisterVo;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import com.liqing.movecomment.annotation.ResponseResult;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@ResponseResult
@RequestMapping("user")
public class UserController {
    @SuppressWarnings("all")
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(UserController.class);
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @ResponseResult(ignore = true)
    @GetMapping("captcha")
    @ApiOperation("获取图像验证码")
    @ApiImplicitParam(name = "uuid", value = "用户名", required = true)
    public void captcha(String uuid, HttpServletResponse response) throws IOException {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha();
        String code = captcha.text();
        // 把验证码的文字放入redis中
        // key: nanqiao:captcha:username value: code
        log.info("username==>{},capchcode==>{}", uuid, captcha.text());
        RedisUtils.setString(RedisConstant.CAPTCHA + uuid, code, 300);
        response.setContentType("image/jpeg");
        captcha.out(response.getOutputStream());
    }

    @PostMapping("login")
    @ApiOperation("用户登录")
    public Map login(@RequestBody UserDTO userDTO, HttpServletResponse response) throws Exception {
        User user = userService.login(userDTO);
        if (ObjectUtils.isEmpty(user)) {
            throw new CustomException("账号或密码错误");
        }
        // 把用户信息放入redis中
        RedisUtils.setObject(RedisConstant.USER + user.getId(), user, 2, TimeUnit.HOURS);
        // 用户登录成功后 基本信息id,name生成 jwttoken
        String token = JwtUtils.createToken(user.getId().toString(), user.getUsername());
        // 扔给前端 header/cookie
        response.addHeader("token", token);
        Cookie cookie = new Cookie("token", token);
        cookie.setPath("/");
        response.addCookie(cookie);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("token", token);
        return map;
    }

    @GetMapping("logout")
    public ResponseEntity<Void> logout(HttpServletResponse response) throws CustomException {
       // User user = (User) ThreadLocalUtils.get();
//        RedisUtils.deleteKey(RedisConstant.USER + user.getId());
        // 删除前端的 header/cookie
        response.addHeader("token", null);
        Cookie cookie = new Cookie("token", null);
        cookie.setPath("/");
        response.addCookie(cookie);
        return ResponseEntity.ok().build();
    }

//<editor-fold defaultstate="collapsed" desc="delombok">
//</editor-fold>
    @PutMapping
    public ResponseEntity<User> edit(User user) {
        return ResponseEntity.ok(this.userService.update(user));
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 页长
     * @return 查询结果
     */
    @GetMapping
    @ApiOperation("用户管理模块,level 1是管理员，2是会员")
    public ResponseEntity<PageInfo<User>> queryAll(Integer page, Integer size, @ApiParam(name = "level", value = "会员等级", required = false) @RequestParam(required = false) Integer level) {
        return ResponseEntity.ok(this.userService.queryAll(page, size, level));
    }

//<editor-fold defaultstate="collapsed" desc="delombok">
//</editor-fold>
    /**
     * 新增数据
     *
     * @param user 实体
     * @return 新增结果
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public User add(@RequestBody UserRegisterVo user) {
        return this.userService.insert(user);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Integer id) {
        return this.userService.queryById(id);
    }

//    /**
//     * 编辑数据
//     *
//     * @param user 实体
//     * @return 编辑结果
//     */
//    @ApiOperation("修改自己信息，不包括密码(个人才行)")
//    @PutMapping
//    public User editSelf(User user) {
//        return this.userService.update(user);
//    }
    @PostMapping("updatePassword")
    @ApiOperation("修改自己密码")
    public User updatePassword(@RequestBody UserChangeDto userChangeDto) {
        return this.userService.updatePassword(userChangeDto);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public Boolean deleteById(Integer id) {
        return this.userService.deleteById(id);
    }
}
